package domain.advertisement;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.swing.ImageIcon;

import technicalservices.database.PersistanseStorage;

import application.config.Config;
import domain.users.User;

public class AdDatabase {

	private List<Ad> ads;

	public AdDatabase() {
		loadAds();
	}

	private void loadAds() {
		ads = PersistanseStorage.getInstance().getAds();
	}

	private void saveAds() {
		PersistanseStorage.getInstance().saveAds(ads);
	}

	/*
	 * This method adds a new advertisement to the ads list. It sets the
	 * advertisement status status in the Ad to PENDING.
	 */
	public void addAd(User advertiser, ImageIcon image, String description,
			AdvertisementScheme scheme) {
		ads.add(new Ad(advertiser, image, description, scheme,
				Config.AdvertiseStatus.PENDING));
		saveAds();
	}

	public void editAd(Ad ad, int index) {
		ads.set(index, ad);
		saveAds();
	}

	public List<Ad> getAds(User advertiser) {
		List<Ad> ads = new ArrayList<Ad>();
		Iterator<Ad> iter = ads.iterator();
		while (iter.hasNext()) {
			Ad ad = (Ad) iter.next();
			if (ad.getAdvertiser().getUserId() == advertiser.getUserId()) {
				ads.add(ad);
			}
		}
		return ads;
	}

	public List<Ad> getAds() {
		return ads;
	}

	public void removeAd(int index) {
		ads.remove(index);
		saveAds();
	}

	public void removeAd(Ad ad) {
		for (int i = 0; i < ads.size(); i++) {
			if (ads.get(i).equals(ad)) {
				ads.remove(i);
			}
		}
	}

	public void printAds() {
		for (int i = 0; i < ads.size(); i++) {
			System.out.println("\nid = " + i + ", " + ads.get(i));
		}
	}

	public int getNumAds() {
		return ads.size();
	}

}
